<template>
  <section class="content" id="content">
    <lq-form :form="form" :rules="rules" ref="addProductsFormRef">
      <template #footer>
        <div style="padding-bottom: 10px;" v-if="form.innerAttrs.disabled==false">
          <el-button type="primary"  @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </lq-form>
  </section>
</template>
<script setup lang="ts">
import LqForm from "@/components/LqForm.vue";
import axios from '@/api/index.js'

import {
  ref,
  reactive,
  onMounted,
  toValue,
  defineExpose,
  defineEmits,
  getCurrentInstance
} from "vue";
import {ElMessage, FormInstance, FormRules} from "element-plus";

// 表单数据结构
const form = ref({
  innerAttrs: {
    labelPosition: 'right',
    labelWidth: 140,
    disabled: false,
    readonly:false
  },
  model: {
    id:'',
    proName:'',
    proPrice:'',
    proImg:'',
    proDate:'',
  },
  formItems: [
            {type: 'input', label: '产品名称', prop: 'proName', span: 12, maxlength: 30, placeholder: '请输入产品名称'},
          {type: 'input', label: '产品价格', prop: 'proPrice', span: 12, maxlength: 30, placeholder: '请输入产品价格'},
          {type: 'input', label: '产品图片', prop: 'proImg', span: 12, maxlength: 30, placeholder: '请输入产品图片'},
          {type: 'input', label: '生产日期', prop: 'proDate', span: 12, maxlength: 30, placeholder: '请输入生产日期'},
     ],
  buttonsAttrs: {
    // align: 'center'
  }
});

// 表单验证规则
const rules = reactive<FormRules>({
proName: [{ required: true, message: '请输入', trigger: 'blur'}],
proPrice: [{ required: true, message: '请输入', trigger: 'blur'}],
proImg: [{ required: true, message: '请输入', trigger: 'blur'}],
proDate: [{ required: true, message: '请输入', trigger: 'blur'}],
});


//向上注册刷新事件
const emit = defineEmits<{
  (e: 'flush', value: Object): void
}>()

// 表单验证规则
const addProductsFormRef = ref<FormInstance>();

const handleSubmit = async () => {
  const valid = await addProductsFormRef.value?.validateForm();
  if (valid) {
    axios.post('/products/updateOrSaveProducts',Object.assign({}, form.value.model, {}))
        .then(({data}) => {
           if (data.code == '200') {
            ElMessage({type: "success", message: "操作成功！", duration: 4000});
            // form.value.innerAttrs.disabled=true;
            emit('flush', {});
          }
        });
  }

}



const handleReset = () => {
  addProductsFormRef.value?.resetFields();
  form.value.innerAttrs.readonly=false;
  form.value.model.id='';  //必须置空否则变成修改了

}
const handleViewOrEdit = (id:string,readyOnly:boolean) => {
  axios.get('/products/getProductsById/'+id)
      .then(({data}) => {
        if (data.code == '200') {
          form.value.model = data.data;
          form.value.innerAttrs.readonly = readyOnly;
        }
      });

}

//暴漏组件操作接口
defineExpose({
  handleViewOrEdit, //编辑
  handleReset  //重置
})
</script>
